//
//  XHRMeViewController.m
//  BuDeJie
//
//  Created by haoran on 16/3/31.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRMeViewController.h"
#import "XHRSettinsViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "XHRSquareItem.h"
#import "XHRSquareCell.h"
#import <SafariServices/SafariServices.h>
#import <WebKit/WebKit.h>
#import "XHRWebViewController.h"

static NSString * const ID = @"cell";
static CGFloat const margin = 1;
static NSInteger const cols = 4;
#define itemWH (XHRScreenW - ((cols - 1) * margin)) / cols

@interface XHRMeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

/** 模型数组 **/
@property (nonatomic, strong) NSMutableArray *itemArray;
/** <#名称#> **/
@property (nonatomic, weak) UICollectionView *collectionView;

@end

@implementation XHRMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置导航条内容
    [self setupNavBar];
    
    //设置 footerView
    [self setupfooterView];
    
    //加载数据
    [self loadData];
    
    // 设置tableView组间距
    // 如果是分组样式,默认每一组都会有头部和尾部间距
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;
    
    // 设置顶部额外滚动区域-25
    self.tableView.contentInset = UIEdgeInsetsMake(XHRMargin - 35, 0, 0, 0);
}

#pragma mark ---- 设置导航条内容
-(void)setupNavBar{
    
    //右边
    UIBarButtonItem * rightItem = [UIBarButtonItem buttonItemWithImage:[UIImage imageNamed:@"mine-setting-icon"] andWithHighlightImage:[UIImage imageNamed:@"mine-setting-icon-click"] addTarget:self andAction:@selector(settings)];
    
    UIBarButtonItem * nightItem = [UIBarButtonItem buttonItemWithImage:[UIImage imageNamed:@"mine-moon-icon"] andWithSelectedImage:[UIImage imageNamed:@"mine-moon-icon-click"] addTarget:self andAction:@selector(night:)];
    
    self.navigationItem.rightBarButtonItems = @[rightItem,nightItem];
    
    //中间
    self.title = @"我的";
    
}
//设置按钮
-(void)settings{
    
    XHRSettinsViewController * settingVC = [[XHRSettinsViewController alloc]init];
    
    //一定要注意:在Push之前去设置这个属性 如果放到XHRSettinsViewController的viewdidload方法中设置无效
    settingVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:settingVC animated:YES];
    
    
}

//设置夜间模式
-(void)night:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
}

#pragma mark ---- 加载数据
-(void)loadData{
    //1.创建会话请求管理者
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    //2.设置请求参数
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    dict[@"a"] = @"square";
    dict[@"c"] = @"topic";
    
    //3.发送请求
    [manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * responseObject) {
        //成功回调
        //取出字典数组
        NSArray * dictArray = responseObject[@"square_list"];
        //字典数组转模型数组
        self.itemArray = [XHRSquareItem mj_objectArrayWithKeyValuesArray:dictArray];
        
        //处理数据,补充空白模型,使得填满一行
        [self resolveData];
        XHRLog(@"%@",[NSThread currentThread]);
        //刷新数据
        [self.collectionView reloadData];
        
        // 设置collectionView高度 => 跟行数 => 总个数 行数:(count - 1) / cols + 1 万能公式
        NSInteger count = self.itemArray.count;
        
        NSInteger row = (count - 1) / cols + 1;
        
        CGFloat collectionH = row *itemWH + (row - 1)* margin;
        
        self.collectionView.xhr_height = collectionH;
        
        //重新设回footerView,不然会由不能滚动的bug,因为第一次设置footerView的时候已经告诉tableview高度,已经确定了滚动范围,需要重新设,让tableview自动计算滚动区域.
        self.tableView.tableFooterView = self.collectionView;
        
        // 重新计算contentSize
        [self.tableView reloadData];
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败回调
        
    }];
}

#pragma mark ---- 处理数据
-(void)resolveData{

    NSInteger count = self.itemArray.count;
    
    NSInteger extre = count % cols;
   
    if (extre) { //过滤掉刚好为4的倍数,余数为0的情况
        extre = cols - extre;
        
        for (int i = 0; i < extre; i++) {
            XHRSquareItem * item = [[XHRSquareItem alloc]init];
            [self.itemArray addObject:item];
        }
    }
    
}

#pragma mark ---- 设置footerView
/*
 1.UICollectionView初始化必须要设置布局
 2.cell必须注册
 3.自定义cell
 */
-(void)setupfooterView{
    //1.创建流水布局
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    
    //确定margin 和 列数
//    CGFloat margin = 1;
//    NSInteger cols = 4;
    //设置cell的尺寸
//    CGFloat itemWH = (XHRScreenW - margin * (cols - 1)) / cols;
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    //设置最小行距和间距
    layout.minimumLineSpacing = margin;
    layout.minimumInteritemSpacing = margin;
    
    UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    //把collectionView 设置到tableview
    self.tableView.tableFooterView = collectionView;
    
    //设置背景色
    collectionView.backgroundColor = XHRColor(215, 215, 215);
    //设置数据源
    collectionView.dataSource = self;
    //设置代理
    collectionView.delegate = self;
    // 
    collectionView.scrollsToTop = NO;
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"XHRSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    self.collectionView = collectionView;
    
    
}

#pragma mark ---- UICollectionViewDataSource
//cell的数量
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArray.count;
    
}

//cell长什么样子
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    XHRSquareCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.item = self.itemArray[indexPath.row];
    
    return  cell;

}

#pragma mark ---- UICollectionViewDelegate
//点击了cell
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //取出模型
    XHRSquareItem * item = self.itemArray[indexPath.row];
    if (![item.url containsString:@"http"]) return;
    
    NSURL *url = [NSURL URLWithString:item.url];
        
    XHRWebViewController * webVC = [[XHRWebViewController alloc]init];
    webVC.url = url;
    [self.navigationController pushViewController:webVC animated:YES];
    
    

}


@end
